package com.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dao.user;
import com.dao.wxuser;
import com.google.zxing.WriterException;
import com.google.zxing.qrcode.QRCodeWriter;
import com.services.WxServices;
import com.utils.GlobalResult;
import com.utils.WechatUtil;
import com.utils.image;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import javax.persistence.Entity;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
import static com.utils.image.*;

@RestController
public class wxLogin {
    @Autowired
    WxServices wxServices;
    private String filePaths;
    com.utils.image image = new image();
    //获取openid
   @RequestMapping("/wx_login")
   public GlobalResult wx_login(@RequestParam("code") String code,
                                @RequestParam("rawData")String rawData,
                                @RequestParam("signature")String signature,
                                @RequestParam("encrypteData")String encrypteData,
                                @RequestParam("iv")String iv, HttpServletRequest request) throws IOException, WriterException {
       System.out.println("进入了");
       System.out.println(code);
       JSONObject rawDataJson = JSON.parseObject(rawData);
       // 1.接收小程序发送的code
       // 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
       JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenIdToUS(code);
       // 3.接收微信接口服务 获取返回的参数
       String openid = SessionKeyOpenId.getString("openid");
       String sessionKey = SessionKeyOpenId.getString("session_key");
       System.out.println("openid"+openid);
       // 4.校验签名 小程序发送的签名signature与服务器端生成的签名signature2 = sha1(rawData + sessionKey)
       String signature2 = DigestUtils.sha1Hex(rawData + sessionKey);
       if (!signature.equals(signature2)) {
           return GlobalResult.build(500, "签名校验失败", null);
       }
       // 5.根据返回的User实体类，判断用户是否是新用户，是的话，将用户信息存到数据库；不是的话，更新最新登录时间
       wxuser user = this.wxServices.getWxUseByOpenId(openid);
       // uuid生成唯一key，用于维护微信小程序用户与服务端的会话
       String skey = UUID.randomUUID().toString();
       if (user == null) {
           // 用户信息入库
          String nickName = rawDataJson.getString("nickName");
          String avatarUrl = rawDataJson.getString("avatarUrl");
          String gender = rawDataJson.getString("gender");
          String city = rawDataJson.getString("city");
          String country = rawDataJson.getString("country");
          String province = rawDataJson.getString("province");
           user = new wxuser();
           user.setOpenid(openid);
           user.setSkey(skey);
           user.setSkey(sessionKey);
           user.setCity(city);
           user.setProvince(province);
           user.setCountry(country);
           user.setNickname(nickName);

         //  this.userMapper.insert(user);
           wxServices.insert(user);
           System.out.println(user);
       } else {
           // 已存在，更新用户登录时间
        //   user.setLastVisitTime(new Date());
           // 重新设置会话skey
           user.setSkey(skey);
        //   this.userMapper.updateById(user);
       }
       //encrypteData比rowData多了appid和openid
       JSONObject userInfo = WechatUtil.getUserInfo(encrypteData, sessionKey, iv);
       //6. 把新的skey返回给小程序
       user user1;
       user1 = wxServices.getUseByOpenId(openid);
       GlobalResult result;
       if(user1!=null) {
            result = GlobalResult.build(200, null, user1); //登录成功且用户信息已填写
            Map maps = new HashMap();
            maps.put("openid",openid);
            maps.put("id_number",user1.getId_number());
            maps.put("phone",user1.getPhone());
            maps.put("room_id",user1.getRoom_id());
            maps.put("name",user1.getName());
            maps.put("year",user1.getYear());
            maps.put("health",user1.getHealth());
            maps.put("sex",user1.getSex());
            filePaths = image.generateQRCodeImage(maps,150,150);

       }else {
           System.out.println("未录入");
            result = GlobalResult.build(201, null, openid); //登录成功但用户信息未填写
       }
       System.out.println(result);
       return result;
   }
   @RequestMapping("/test")
    public String get(){
       return "hh";
   }
   @RequestMapping("/set_userInfo")
   public GlobalResult setUserInfo(@RequestParam("openid")String openid,
                             @RequestParam("id_number")String id_number,
                             @RequestParam("phone")String phone,
                             @RequestParam("room_id")String room_id,
                             @RequestParam("name")String name,
                             @RequestParam("year")String year,
                             @RequestParam("sex")String sex,
                             @RequestParam("health")String health) throws IOException, WriterException {
       System.out.println(openid+phone+room_id+name+year+sex+health);
       if(openid==null){
           GlobalResult globalResult = new GlobalResult(500,null,"无openid");
           return globalResult;
       }
       user user1 = new user();
       user1.setOpenid(openid);
       user1.setHealth(health);
       user1.setId_number(id_number);
       user1.setName(name);
       user1.setPhone(phone);
       user1.setRoom_id(room_id);
       user1.setSex(sex);
       user1.setYear(year);
       user user2 = new user();
       user2= wxServices.getUseByOpenId(openid);
       if(user2!=null){

       }else {
           wxServices.insertIntoUser(user1);
       }
       GlobalResult result;
       Map maps = new HashMap();
       maps.put("openid",openid);
       maps.put("id_number",user1.getId_number());
       maps.put("phone",user1.getPhone());
       maps.put("room_id",user1.getRoom_id());
       maps.put("name",user1.getName());
       maps.put("year",user1.getYear());
       maps.put("health",user1.getHealth());
       maps.put("sex",user1.getSex());
       filePaths = image.generateQRCodeImage(maps,150,150);
       result = GlobalResult.build(200, null, user1);
       return result;
   }
    @RequestMapping("/path/{openid}")
    public String getPATH(@PathVariable("openid") String openid, HttpServletRequest request, HttpServletResponse response, Model model) throws FileNotFoundException {
        File path1 = new File(ResourceUtils.getURL("classpath:").getPath());
        if(!path1.exists()) {
            path1 = new File("");
        }
        System.out.println(path1.getAbsolutePath());
        File upload = new File(path1.getAbsolutePath(),"static/upload/");
        if(!upload.exists()) {
            upload.mkdirs();
        }

        String  filePath = upload.getAbsolutePath()+"\\"+openid+".png";
        FileInputStream fis = null;
        OutputStream os = null;
        try{
            fis = new FileInputStream(filePath);
            os = response.getOutputStream();
            int count = 0;
            byte[] buffer = new byte[1024*8];
            while((count=fis.read(buffer))!=-1){
                os.write(buffer,0,count);
                os.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try{
            fis.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  filePath;
    }
    @RequestMapping(value = "/show")
    @ResponseBody
    public String createFolw(HttpServletRequest request,
                             HttpServletResponse response, Model model) {
        // response.setContentType("image/*");
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            fis = new FileInputStream(filePaths);
            os = response.getOutputStream();
            int count = 0;
            byte[] buffer = new byte[1024 * 8];
            while ((count = fis.read(buffer)) != -1) {
                os.write(buffer, 0, count);
                os.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            fis.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "ok";
    }
}
